<script setup>
import EmptyContent from "../components/EmptyContent.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ref, computed, onMounted, nextTick, onUnmounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getHistoryListApi,
  deleteHistoryApi,
  clearHistoryApi,
} from "@/api/history";
import { useVideoPlayerStore } from "@/store/modules/videoPlayer";

const videoPlayerStore = useVideoPlayerStore();

// 修改 HistoryView.vue 中的 handleVideoClick 方法
const handleVideoClick = (videoId, item) => {
  console.log("点击历史视频:", videoId, item);

  // 构建一个完整的视频对象
  const videoObject = {
    id: videoId,
    video_id: videoId,
    title: item.title,
    src: item.videoUrl, // 假设历史记录中有视频URL字段
    oss_url: item.videoUrl, // 确保两种格式都有
    cover_url: item.coverUrl,
    coverUrl: item.coverUrl,
    duration: item.duration,
    author: item.author,
    user: {
      id: item.authorId, // 假设有作者ID
      username: item.author,
      avatar: item.authorAvatar || "", // 假设有作者头像字段
    },
  };

  // 传递完整的视频对象给 store
  videoPlayerStore.openVideoModal(videoId, videoObject);
};
// 分页参数
const pageParams = ref({
  currentPage: 1,
  pageSize: 10,
  hasMore: true,
  loading: false,
  initialized: false,
});

// 历史记录数据
const historyItems = ref([]);
const historyListRef = ref(null);

// 检查是否有历史记录
const hasHistory = computed(() => {
  return pageParams.value.initialized && historyItems.value.length > 0;
});

// 是否为初始加载中状态
const isInitialLoading = computed(() => {
  return !pageParams.value.initialized && pageParams.value.loading;
});

// 获取历史记录数据
async function fetchHistoryData(page = 1, append = false) {
  // 如果已经没有更多数据或正在加载中，则直接返回
  if ((!pageParams.value.hasMore && page > 1) || pageParams.value.loading)
    return;

  pageParams.value.loading = true;

  try {
    // 调用真实API
    const response = await getHistoryListApi({
      page: page,
      limit: pageParams.value.pageSize,
    });

    // 假设API返回的数据结构为: { items: [...], total: 100, currentPage: 1, ... }
    const { items, total, currentPage } = response;

    if (append) {
      // 追加数据
      historyItems.value = [...historyItems.value, ...items];
    } else {
      // 替换数据
      historyItems.value = items;
    }

    // 更新分页信息
    pageParams.value.currentPage = currentPage;
    pageParams.value.hasMore = historyItems.value.length < total;
    pageParams.value.initialized = true;
  } catch (error) {
    console.error("获取历史记录失败:", error);
    ElMessage.error("获取历史记录失败，请稍后重试");
  } finally {
    pageParams.value.loading = false;
  }
}

// 滚动处理的节流函数
function throttle(fn, delay) {
  let lastCall = 0;
  return function (...args) {
    const now = new Date().getTime();
    if (now - lastCall < delay) {
      return;
    }
    lastCall = now;
    return fn.apply(this, args);
  };
}

// 监听滚动事件，实现无限加载
function setupScrollListener() {
  // 使用ref获取元素更可靠
  if (!historyListRef.value) {
    console.warn("历史记录列表元素不存在，无法设置滚动监听");
    return;
  }

  console.log("设置滚动监听器");
  historyListRef.value.addEventListener("scroll", handleScroll);

  return () => {
    console.log("移除滚动监听器");
    historyListRef.value &&
      historyListRef.value.removeEventListener("scroll", handleScroll);
  };
}

// 处理滚动事件（添加节流）
const handleScroll = throttle(function (e) {
  const element = e.target;
  // 当滚动到距离底部100px以内时，加载更多数据
  if (element.scrollHeight - element.scrollTop - element.clientHeight < 100) {
    if (pageParams.value.hasMore && !pageParams.value.loading) {
      console.log("触发加载更多...");
      loadMore();
    }
  }
}, 300); // 300ms节流

// 加载更多数据
function loadMore() {
  const nextPage = pageParams.value.currentPage + 1;
  console.log(`准备加载第${nextPage}页数据...`);
  fetchHistoryData(nextPage, true).then(() => {
    console.log(`已加载数据总条数: ${historyItems.value.length}`);
    console.log(`是否还有更多数据: ${pageParams.value.hasMore}`);
  });
}

// 按日期分组历史记录
const groupedHistory = computed(() => {
  const groups = {};

  historyItems.value.forEach((item) => {
    // 提取日期部分
    const datePart = item.viewTime.split("T")[0];

    // 格式化为更友好的显示
    const date = new Date(datePart);
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    // 显示为"今天"、"昨天"或具体日期
    let dateLabel;
    if (date.getTime() === today.getTime()) {
      dateLabel = "今天";
    } else if (date.getTime() === yesterday.getTime()) {
      dateLabel = "昨天";
    } else {
      dateLabel = `${date.getMonth() + 1}月${date.getDate()}日`;
    }

    if (!groups[dateLabel]) {
      groups[dateLabel] = [];
    }

    groups[dateLabel].push(item);
  });

  // 转换为数组形式，便于在模板中使用
  return Object.entries(groups).map(([date, items]) => ({
    date,
    items,
  }));
});

// 清空历史记录
async function clearHistory() {
  ElMessageBox.confirm(
    "确定要清空全部观看历史吗？此操作不可恢复。",
    "清空历史记录",
    {
      confirmButtonText: "确定清空",
      cancelButtonText: "取消",
      type: "warning",
      customClass: "clear-history-dialog",
      confirmButtonClass: "confirm-clear-btn",
      cancelButtonClass: "cancel-clear-btn",
    }
  )
    .then(async () => {
      try {
        // 调用API清空历史记录
        await clearHistoryApi();

        // 清空本地数据
        historyItems.value = [];
        pageParams.value = {
          currentPage: 1,
          pageSize: 10,
          hasMore: true,
          loading: false,
          initialized: true,
        };

        ElMessage({
          type: "success",
          message: "历史记录已清空",
        });
      } catch (error) {
        console.error("清空历史记录失败:", error);
        ElMessage.error("清空历史记录失败，请稍后重试");
      }
    })
    .catch(() => {
      // 用户取消，不执行任何操作
    });
}

// 删除单条历史记录
async function deleteHistoryItem(id) {
  try {
    console.log("删除历史记录:", id);
    // 调用API删除历史记录
    await deleteHistoryApi(id);

    // 本地更新
    const index = historyItems.value.findIndex((item) => item.id === id);
    if (index !== -1) {
      historyItems.value.splice(index, 1);

      // 如果删除后列表为空，则重置
      if (historyItems.value.length === 0) {
        pageParams.value.initialized = true;
      }

      ElMessage({
        type: "success",
        message: "已从历史记录中移除",
      });
    }
  } catch (error) {
    console.error("删除历史记录失败:", error);
    ElMessage.error("删除失败，请稍后重试");
  }
}

// 查看视频详情
function viewVideoDetail(videoId) {
  console.log("查看视频详情", videoId);
  // 这里添加跳转到视频详情页的逻辑
  // router.push(`/video/${videoId}`);
}

// 格式化时间
function formatTime(timeString) {
  const date = new Date(timeString);
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
}

// 添加手动测试功能
function testLoadMore() {
  loadMore();
}

// 组件挂载时加载初始数据
onMounted(() => {
  fetchHistoryData();

  const cleanup = setupScrollListener();
});
</script>

<template>
  <div class="content-panel">
    <h3>
      观看历史
      <div class="action-buttons">
        <!-- 添加测试按钮方便测试 -->
        <!-- <button v-if="hasHistory" class="test-button" @click="testLoadMore">
          测试加载更多
        </button> -->
        <button v-if="hasHistory" class="clear-button" @click="clearHistory">
          清空历史记录
        </button>
      </div>
    </h3>

    <!-- 加载中状态 -->
    <div v-if="isInitialLoading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 有历史记录时显示列表 -->
    <div v-show="hasHistory" ref="historyListRef" class="history-list">
      <!-- 按日期分组显示历史记录 -->
      <div
        v-for="group in groupedHistory"
        :key="group.date"
        class="history-group"
      >
        <div class="date-divider">
          <span class="date-label">{{ group.date }}</span>
          <div class="divider-line"></div>
        </div>

        <div class="history-items">
          <div
            v-for="item in group.items"
            :key="item.id"
            class="history-item"
            @click="handleVideoClick(item.videoId, item)"
          >
            <div class="video-cover">
              <img :src="item.coverUrl" alt="视频封面" />
              <span class="video-duration">{{ item.duration }}</span>

              <!-- 观看进度条 -->
              <div class="progress-bar">
                <div
                  class="progress-inner"
                  :style="{ width: `${item.progress}%` }"
                ></div>
              </div>
            </div>

            <div class="video-info">
              <h4 class="video-title">{{ item.title }}</h4>
              <p class="video-author">{{ item.author }}</p>
              <p class="video-time">观看于 {{ formatTime(item.viewTime) }}</p>
            </div>

            <div class="video-actions">
              <button
                class="delete-btn"
                @click.stop="deleteHistoryItem(item.id)"
              >
                <i class="delete-icon">🗑️</i>
                <!-- 使用emoji代替SVG图标 -->
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部加载提示 -->
      <div v-if="pageParams.loading" class="loading-more">
        <div class="loading-spinner small"></div>
        <span>加载更多...</span>
      </div>
      <div
        v-else-if="!pageParams.hasMore && historyItems.length > 0"
        class="no-more"
      >
        没有更多历史记录了
      </div>
    </div>

    <!-- 无历史记录时显示空状态 -->
    <EmptyContent
      v-if="groupedHistory.length <= 0 && !pageParams.loading"
      icon="🕒"
      text="暂无观看历史"
      :showButton="false"
    />
  </div>
</template>

<style scoped lang="scss">
.content-panel {
  display: flex;
  flex-direction: column;
  height: 100%;

  h3 {
    margin-top: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 1.4rem;
    color: #ffffff;
    border-left: 4px solid #0096ff;
    padding-left: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .action-buttons {
      display: flex;
      gap: 10px;
    }

    .clear-button,
    .test-button {
      font-size: 0.9rem;
      background: transparent;
      color: #99a3a7;
      border: 1px solid #99a3a7;
      border-radius: 4px;
      padding: 4px 12px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        color: #ff4949;
        border-color: #ff4949;
      }
    }

    .test-button {
      background-color: rgba(0, 150, 255, 0.1);
      color: #0096ff;
      border-color: #0096ff;

      &:hover {
        background-color: rgba(0, 150, 255, 0.2);
        color: #0096ff;
        border-color: #0096ff;
      }
    }
  }

  .history-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 16px 16px;
  }

  .history-group {
    margin-bottom: 24px;

    .date-divider {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .date-label {
        font-size: 1rem;
        font-weight: 500;
        color: #ffffff;
        padding-right: 12px;
        white-space: nowrap;
      }

      .divider-line {
        flex-grow: 1;
        height: 1px;
        background-color: rgba(255, 255, 255, 0.1);
      }
    }
  }

  .history-items {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .history-item {
    display: flex;
    background-color: #1f2129;
    border-radius: 10px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background-color: #272933;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);

      .delete-btn {
        opacity: 1;
      }
    }

    .video-cover {
      position: relative;
      width: 180px;
      height: 100px;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .video-duration {
        position: absolute;
        bottom: 25px;
        right: 8px;
        background-color: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 1px 5px;
        border-radius: 4px;
        font-size: 0.75rem;
      }

      .progress-bar {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background-color: rgba(255, 255, 255, 0.2);

        .progress-inner {
          height: 100%;
          background: linear-gradient(90deg, #0096ff, #6c47ff);
        }
      }
    }

    .video-info {
      flex: 1;
      padding: 12px 16px;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .video-title {
        font-size: 1rem;
        font-weight: 500;
        color: #ffffff;
        margin: 0 0 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .video-author {
        font-size: 0.85rem;
        color: #99a3a7;
        margin: 0 0 4px;
      }

      .video-time {
        font-size: 0.8rem;
        color: #6c7a83;
      }

      .progress-text {
        font-size: 0.8rem;
        color: #0096ff;

        &.completed {
          color: #52c41a;
        }
      }
    }

    .video-actions {
      display: flex;
      align-items: center;
      padding-right: 12px;

      .delete-btn {
        background: transparent;
        border: none;
        color: #99a3a7;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        cursor: pointer;
        opacity: 0.6;
        /* 修改这里，使按钮始终有一定透明度 */
        transition: all 0.2s ease;

        &:hover {
          background-color: rgba(255, 73, 73, 0.1);
          color: #ff4949;
          opacity: 1;
          /* 悬停时完全显示 */
        }
      }
    }
  }

  .loading-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #99a3a7;
  }

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(0, 150, 255, 0.3);
    border-radius: 50%;
    border-top-color: #0096ff;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 12px;

    &.small {
      width: 24px;
      height: 24px;
      border-width: 2px;
      margin-bottom: 0;
      margin-right: 10px;
    }
  }

  .loading-more,
  .no-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 16px;
    color: #99a3a7;
    font-size: 0.9rem;
  }

  .no-more {
    color: #6c7a83;
    margin-top: 8px;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 自定义对话框样式 */
:global(.clear-history-dialog) {
  border-radius: 12px;
  background-color: #2a2c36;
}

:global(.clear-history-dialog .el-message-box__header) {
  background-color: #2a2c36;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:global(.clear-history-dialog .el-message-box__title) {
  color: #ffffff;
}

:global(.clear-history-dialog .el-message-box__content) {
  color: #e0e0e0;
  padding-top: 20px;
}

:global(.clear-history-dialog .el-message-box__message) {
  color: #e0e0e0;
}

:global(.confirm-clear-btn) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:global(.confirm-clear-btn:hover) {
  background-color: #e04747;
  border-color: #e04747;
}

:global(.cancel-clear-btn) {
  border-color: #909399;
  color: #909399;
}
</style>
